package com.example.lottery.controller;


import com.example.lottery.common.pojo.CommonResult;
import com.example.lottery.common.utils.JacksonUtil;
import com.example.lottery.controller.param.DrawPrizeParam;
import com.example.lottery.controller.param.ShowWinningRecordsParam;
import com.example.lottery.controller.result.WinningRecordResult;
import com.example.lottery.service.DrawPrizeService;
import com.example.lottery.service.dto.WinningRecordDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/draw")
public class DrawPrizeController {

    @Autowired
    private DrawPrizeService drawPrizeService;

    /**
     * 抽奖请求处理(中奖结果处理，中奖者通知，抽奖异常，回滚，补救措施(重新落库)，状态扭转等)
     * @param param
     * @return
     */
    @RequestMapping("/prize")
    public CommonResult<Boolean> drawPrize(@RequestBody @Validated DrawPrizeParam param) {
        log.info("drawPrize, param: {}", param);
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }


    /**
     * 获奖列表展示
     * @param param
     * @return
     */
    @RequestMapping("/winning-records/show")
    public CommonResult<List<WinningRecordResult>> showWinningRecords(@Validated @RequestBody ShowWinningRecordsParam param) {
        log.info("showWinningRecords ShowWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));
        List<WinningRecordDTO> winningRecordDTOList = drawPrizeService.getRecords(param);
        return CommonResult.success(convertToWinningRecordResultList(winningRecordDTOList));
    }


    /**
     * 获奖列表展示返回结果转换
     * @param winningRecordDTOList
     * @return
     */
    private List<WinningRecordResult> convertToWinningRecordResultList(List<WinningRecordDTO> winningRecordDTOList) {
        if (CollectionUtils.isEmpty(winningRecordDTOList)) {
            return Arrays.asList();
        }

        return winningRecordDTOList.stream()
                .map(winningRecordDTO -> {
                    WinningRecordResult result = new WinningRecordResult();
                    result.setWinnerId(winningRecordDTO.getWinnerId());
                    result.setWinnerName(winningRecordDTO.getWinnerName());
                    result.setPrizeName(winningRecordDTO.getPrizeName());
                    result.setPrizeTier(winningRecordDTO.getPrizeTier().getMessage());
                    result.setWinningTime(winningRecordDTO.getWinningTime());
                    return result;
                }).collect(Collectors.toList());
    }
}
